#include "liburing_coro.hpp"
#include <cstdio>
#include <vector>
#include <iostream>

//   Output a string of characters of len length to stdout.
//   We use buffered output here to be efficient,
//   since we need to output character-by-character.
void output_to_console(char *buf, int len)
{
    while (len--)
    {
        fputc(*buf++, stdout);
    }
}

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s [file name] <[file name] ...>\n", argv[0]);
        return 1;
    }

    // Initialize io_uring
    io_uring ring;
    io_uring_queue_init(argc - 1, &ring, 0);

    std::vector<io_uring_wrapper> reqs;

    // allocating buffer for reading files
    char *buf = new char[1024 * (argc - 1)];

    for (int i = 1; i < argc; ++i)
    {
        // create requests for each file
        reqs.emplace_back(request_file_by_name(argv[i], 1, 1024, buf + 1024 * (i - 1), &ring));
    }

    // submit io_uring requests
    io_uring_submit(&ring);

    for (int i = 0; i < argc - 1; ++i)
    {
        // will block until the file is ready, return the readed size
        auto size = reqs[i]();

        output_to_console(buf + 1024 * i, size);
        reqs[i](); // release resources
    }

    // clean up the buffer
    delete[] buf;

    // clean up the ring
    io_uring_queue_exit(&ring);
}
